package com.yvan.leto.api;

import com.yvan.leto.SegmentHelper;
import com.yvan.leto.server.dao.ProjectPersistent;
import com.yvan.leto.server.dao.RepositoryPersistent;
import com.yvan.leto.server.domain.Segment;
import com.yvan.leto.server.service.IParser;
import com.yvan.leto.server.service.LogbackParser;
import com.yvan.leto.server.service.ParserContext;
import com.yvan.leto.server.service.SpringBootParser;
import lombok.val;

public class ConfigApi {

    private final String letoServer;
    private final RepositoryPersistent repositoryPersistent;
    private final ProjectPersistent projectPersistent;

    public ConfigApi(String letoServer) {
        this.letoServer = letoServer;
        this.repositoryPersistent = new RepositoryPersistent(letoServer);
        this.projectPersistent = new ProjectPersistent(letoServer);
    }

    public String getSegmentContent(String env, String appId, String segmentName) {
        IParser parser;

        if (SegmentHelper.LOGBACK.equals(segmentName)) {
            parser = new LogbackParser();
        } else if (SegmentHelper.SPRING_BOOT.equals(segmentName)) {
            parser = new SpringBootParser();
        } else {
            return "";
        }

        val project = projectPersistent.projectFindByName(appId);

        for (Segment segment : project.getSegments()) {
            if (segmentName.equals(segment.getName())) {
                ParserContext parserContext = new ParserContext();
                parserContext.setRepositoryPersistent(this.repositoryPersistent);
                parserContext.setEnv(env);
                parserContext.setProject(project);
                parserContext.setSegment(segment);
                return parser.process(parserContext);
            }
        }

        return "";
    }
}
